<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋网络对战</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#8B5A2B',      // 棋盘木色
                        secondary: '#D2B48C',    // 浅木色
                        accent: '#4A3728',       // 深棕色
                        board: '#E6A65D',        // 棋盘底色
                        black: '#000000',        // 黑棋
                        white: '#FFFFFF',        // 白棋
                        highlight: '#FFD700',    // 高亮色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'piece': '0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)',
                        'board': '0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.1)',
                    }
                },
            }
        }
    </script>
    
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .board-grid {
                background-image: linear-gradient(to right, #000 1px, transparent 1px),
                                linear-gradient(to bottom, #000 1px, transparent 1px);
            }
            .piece-transition {
                transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
            }
            .board-hover:hover::before {
                content: '';
                position: absolute;
                width: 80%;
                height: 80%;
                border-radius: 50%;
                background-color: rgba(0, 0, 0, 0.1);
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-amber-50 to-orange-100 min-h-screen font-sans text-accent flex flex-col items-center justify-start pt-8 pb-16">
    <!-- 页面标题 -->
    <header class="text-center mb-8 w-full max-w-4xl px-4">
        <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary mb-2 tracking-tight">五子棋网络对战</h1>
        <p class="text-accent/80 text-lg max-w-2xl mx-auto">在线与好友对战，落子连五获胜</p>
    </header>
    
    <!-- 网络对战面板 -->
    <div class="w-full max-w-6xl px-4 mb-4">
        <div class="bg-white rounded-xl shadow-lg p-4 flex flex-wrap items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <div>
                    <p class="text-sm text-gray-500">连接状态</p>
                    <div class="flex items-center">
                        <span id="connection-status" class="inline-block w-3 h-3 rounded-full bg-red-500 mr-2"></span>
                        <span id="connection-text">未连接</span>
                    </div>
                </div>
                
                <div>
                    <p class="text-sm text-gray-500">房间ID</p>
                    <div class="flex items-center gap-2">
                        <input type="text" id="room-id" placeholder="输入房间ID" class="border border-gray-300 rounded px-2 py-1 text-sm w-32">
                        <button id="join-room" class="bg-primary text-white text-sm px-3 py-1 rounded hover:bg-primary/90 transition">加入</button>
                        <button id="create-room" class="bg-secondary text-accent text-sm px-3 py-1 rounded hover:bg-secondary/90 transition">创建</button>
                    </div>
                </div>
            </div>
            
            <div class="flex items-center gap-6">
                <div>
                    <p class="text-sm text-gray-500">玩家1 (黑棋)</p>
                    <p id="player1-name">等待中...</p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">玩家2 (白棋)</p>
                    <p id="player2-name">等待中...</p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">你的身份</p>
                    <p id="your-role">未分配</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 主游戏区域 -->
    <main class="w-full max-w-6xl flex flex-col lg:flex-row items-center lg:items-start justify-center gap-8 px-4">
        <!-- 游戏信息面板 -->
        <div class="w-full lg:w-64 bg-white rounded-xl shadow-lg p-6 order-2 lg:order-1">
            <div class="mb-6">
                <h2 class="text-xl font-bold mb-4 pb-2 border-b border-gray-200 flex items-center">
                    <i class="fa fa-info-circle mr-2 text-primary"></i>游戏状态
                </h2>
                
                <!-- 当前玩家指示器 -->
                <div class="mb-4">
                    <p class="text-sm text-gray-500 mb-1">当前回合</p>
                    <div class="flex items-center">
                        <div id="current-player-indicator" class="w-6 h-6 rounded-full bg-black mr-2 piece-transition"></div>
                        <span id="current-player-text" class="font-medium">黑棋</span>
                    </div>
                </div>
                
                <!-- 游戏结果 -->
                <div id="game-result" class="hidden mb-4 p-3 rounded-lg bg-gray-100">
                    <p id="result-text" class="font-medium text-center"></p>
                </div>
                
                <!-- 已落子数 -->
                <div class="mb-4">
                    <p class="text-sm text-gray-500 mb-1">已落子数</p>
                    <p id="moves-count" class="font-medium">0</p>
                </div>
                
                <!-- 网络状态信息 -->
                <div class="mb-4 p-3 rounded-lg bg-blue-50">
                    <p id="network-message" class="text-sm text-blue-700">请创建或加入房间开始游戏</p>
                </div>
            </div>
            
            <!-- 控制按钮 -->
            <div class="space-y-3">
                <h2 class="text-xl font-bold mb-4 pb-2 border-b border-gray-200 flex items-center">
                    <i class="fa fa-cog mr-2 text-primary"></i>游戏控制
                </h2>
                
                <button id="restart-btn" class="w-full py-3 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                    <i class="fa fa-refresh"></i>
                    <span>重新开始</span>
                </button>
                
                <button id="undo-btn" class="w-full py-3 bg-secondary hover:bg-secondary/90 text-accent rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                    <i class="fa fa-undo"></i>
                    <span>悔棋</span>
                </button>
                
                <button id="hint-btn" class="w-full py-3 bg-amber-100 hover:bg-amber-200 text-accent rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                    <i class="fa fa-lightbulb-o"></i>
                    <span>提示</span>
                </button>
                
                <button id="leave-room" class="w-full py-3 bg-red-100 hover:bg-red-200 text-red-700 rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                    <i class="fa fa-sign-out"></i>
                    <span>离开房间</span>
                </button>
            </div>
            
            <!-- 游戏规则 -->
            <div class="mt-6 pt-6 border-t border-gray-200">
                <h2 class="text-xl font-bold mb-4 flex items-center">
                    <i class="fa fa-book mr-2 text-primary"></i>游戏规则
                </h2>
                <ul class="text-sm space-y-2 text-gray-600">
                    <li class="flex items-start">
                        <i class="fa fa-check-circle text-primary mt-1 mr-2"></i>
                        <span>黑白双方轮流在棋盘上落子</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fa fa-check-circle text-primary mt-1 mr-2"></i>
                        <span>先在横、竖或斜方向连成五子者获胜</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fa fa-check-circle text-primary mt-1 mr-2"></i>
                        <span>黑棋先行，落子后不能移动或拿掉</span>
                    </li>
                </ul>
            </div>
        </div>
        
        <!-- 棋盘区域 -->
        <div class="order-1 lg:order-2">
            <div class="relative">
                <!-- 棋盘容器 -->
                <div id="board-container" class="relative bg-board rounded-lg shadow-board overflow-hidden">
                    <!-- 棋盘将通过JavaScript动态生成 -->
                    <div id="board" class="board-grid absolute inset-0"></div>
                    
                    <!-- 棋子容器 -->
                    <div id="pieces" class="absolute inset-0"></div>
                    
                    <!-- 胜利连线将通过JavaScript动态生成 -->
                    <div id="win-line" class="absolute inset-0 pointer-events-none"></div>
                </div>
                
                <!-- 加载指示器 -->
                <div id="loader" class="hidden absolute inset-0 bg-accent/70 rounded-lg flex items-center justify-center">
                    <div class="w-16 h-16 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
                </div>
            </div>
            
            <!-- 移动端控制按钮 -->
            <div class="lg:hidden mt-4 grid grid-cols-3 gap-3">
                <button id="mobile-restart-btn" class="py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 flex items-center justify-center gap-1 shadow-md">
                    <i class="fa fa-refresh"></i>
                    <span class="text-sm">重开</span>
                </button>
                
                <button id="mobile-undo-btn" class="py-2 bg-secondary hover:bg-secondary/90 text-accent rounded-lg transition-all duration-300 flex items-center justify-center gap-1 shadow-md">
                    <i class="fa fa-undo"></i>
                    <span class="text-sm">悔棋</span>
                </button>
                
                <button id="mobile-hint-btn" class="py-2 bg-amber-100 hover:bg-amber-200 text-accent rounded-lg transition-all duration-300 flex items-center justify-center gap-1 shadow-md">
                    <i class="fa fa-lightbulb-o"></i>
                    <span class="text-sm">提示</span>
                </button>
            </div>
        </div>
    </main>
    
    <!-- 页脚 -->
    <footer class="mt-12 text-center text-gray-500 text-sm">
        <p>© 2023 五子棋网络对战 | 享受在线对弈的乐趣</p>
    </footer>
    
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏配置
            const BOARD_SIZE = 15; // 15x15的棋盘
            let cellSize; // 每个格子的大小，会根据屏幕尺寸计算
            let boardPadding; // 棋盘内边距
            
            // 游戏状态
            let gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0)); // 0:空, 1:黑, 2:白
            let currentPlayer = 1; // 1:黑, 2:白
            let gameActive = false; // 网络对战中默认不活跃，直到房间准备就绪
            let moveHistory = []; // 记录落子历史，用于悔棋
            let movesCount = 0;
            
            // 网络对战状态
            let socket;
            let isConnected = false;
            let roomId = null;
            let playerId = null; // 1或2
            let playerName = '玩家' + Math.floor(Math.random() * 1000); // 随机生成玩家名
            
            // DOM元素
            const boardContainer = document.getElementById('board-container');
            const board = document.getElementById('board');
            const pieces = document.getElementById('pieces');
            const winLine = document.getElementById('win-line');
            const currentPlayerIndicator = document.getElementById('current-player-indicator');
            const currentPlayerText = document.getElementById('current-player-text');
            const gameResult = document.getElementById('game-result');
            const resultText = document.getElementById('result-text');
            const movesCountEl = document.getElementById('moves-count');
            const restartBtn = document.getElementById('restart-btn');
            const undoBtn = document.getElementById('undo-btn');
            const hintBtn = document.getElementById('hint-btn');
            const leaveRoomBtn = document.getElementById('leave-room');
            const mobileRestartBtn = document.getElementById('mobile-restart-btn');
            const mobileUndoBtn = document.getElementById('mobile-undo-btn');
            const mobileHintBtn = document.getElementById('mobile-hint-btn');
            const loader = document.getElementById('loader');
            const connectionStatus = document.getElementById('connection-status');
            const connectionText = document.getElementById('connection-text');
            const roomIdInput = document.getElementById('room-id');
            const joinRoomBtn = document.getElementById('join-room');
            const createRoomBtn = document.getElementById('create-room');
            const player1NameEl = document.getElementById('player1-name');
            const player2NameEl = document.getElementById('player2-name');
            const yourRoleEl = document.getElementById('your-role');
            const networkMessageEl = document.getElementById('network-message');
            
            // 初始化棋盘
            function initializeBoard() {
                // 根据屏幕尺寸计算棋盘大小
                const maxBoardSize = Math.min(
                    window.innerWidth - 40, 
                    window.innerHeight - 200,
                    600
                );
                
                cellSize = maxBoardSize / BOARD_SIZE;
                boardPadding = cellSize / 2;
                const totalSize = cellSize * (BOARD_SIZE - 1) + boardPadding * 2;
                
                // 设置棋盘容器尺寸
                boardContainer.style.width = `${totalSize}px`;
                boardContainer.style.height = `${totalSize}px`;
                
                // 设置网格背景
                board.style.backgroundSize = `${cellSize}px ${cellSize}px`;
                board.style.backgroundPosition = `${boardPadding}px ${boardPadding}px`;
                
                // 清空棋盘
                pieces.innerHTML = '';
                winLine.innerHTML = '';
                
                // 创建棋盘格点
                for (let y = 0; y < BOARD_SIZE; y++) {
                    for (let x = 0; x < BOARD_SIZE; x++) {
                        const cell = document.createElement('div');
                        cell.classList.add('absolute', 'board-hover', 'cursor-pointer');
                        cell.style.width = `${cellSize}px`;
                        cell.style.height = `${cellSize}px`;
                        cell.style.left = `${x * cellSize + boardPadding - cellSize / 2}px`;
                        cell.style.top = `${y * cellSize + boardPadding - cellSize / 2}px`;
                        cell.dataset.x = x;
                        cell.dataset.y = y;
                        
                        // 添加点击事件
                        cell.addEventListener('click', () => handleCellClick(x, y));
                        
                        board.appendChild(cell);
                        
                        // 添加天元和星位
                        if ((x === 3 || x === 7 || x === 11) && (y === 3 || y === 7 || y === 11)) {
                            const star = document.createElement('div');
                            star.classList.add('absolute', 'rounded-full', 'bg-black');
                            star.style.width = `${cellSize / 8}px`;
                            star.style.height = `${cellSize / 8}px`;
                            star.style.left = `${x * cellSize + boardPadding}px`;
                            star.style.top = `${y * cellSize + boardPadding}px`;
                            star.style.transform = 'translate(-50%, -50%)';
                            board.appendChild(star);
                        }
                    }
                }
                
                // 重置游戏状态
                resetGameState();
            }
            
            // 重置游戏状态
            function resetGameState() {
                gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
                currentPlayer = 1;
                gameActive = !!roomId; // 如果在房间中，则游戏可活跃
                moveHistory = [];
                movesCount = 0;
                
                // 更新UI
                updatePlayerIndicator();
                gameResult.classList.add('hidden');
                movesCountEl.textContent = '0';
                
                // 更新网络消息
                if (roomId && playerId) {
                    showNetworkMessage(`游戏已重置，${currentPlayer === 1 ? '黑棋' : '白棋'}先行`);
                }
            }
            
            // 处理单元格点击
            function handleCellClick(x, y) {
                // 检查游戏是否活跃，是否是当前玩家回合，以及单元格是否为空
                if (!gameActive || currentPlayer !== playerId || gameBoard[y][x] !== 0) {
                    if (currentPlayer !== playerId) {
                        showNetworkMessage("等待对方落子...", "orange");
                    }
                    return;
                }
                
                // 发送落子信息到服务器
                sendMove(x, y);
            }
            
            // 放置棋子（本地）
            function placePiece(x, y, player) {
                // 更新游戏板状态
                gameBoard[y][x] = player;
                
                // 创建棋子元素
                const piece = document.createElement('div');
                piece.classList.add('absolute', 'rounded-full', 'piece-transition', 'shadow-piece');
                piece.style.width = `${cellSize * 0.8}px`;
                piece.style.height = `${cellSize * 0.8}px`;
                piece.style.left = `${x * cellSize + boardPadding}px`;
                piece.style.top = `${y * cellSize + boardPadding}px`;
                piece.style.transform = 'translate(-50%, -50%) scale(0)';
                
                // 设置棋子颜色
                if (player === 1) {
                    piece.classList.add('bg-black');
                } else {
                    piece.classList.add('bg-white', 'border', 'border-gray-300');
                }
                
                // 添加到棋盘
                pieces.appendChild(piece);
                
                // 添加动画效果
                setTimeout(() => {
                    piece.style.transform = 'translate(-50%, -50%) scale(1)';
                }, 10);
                
                // 为最后一步添加标记
                highlightLastMove(x, y);
            }
            
            // 高亮最后一步
            function highlightLastMove(x, y) {
                // 移除之前的高亮
                document.querySelectorAll('.last-move').forEach(el => {
                    el.classList.remove('last-move');
                });
                
                // 找到最后一个棋子并添加高亮
                const lastPiece = pieces.lastChild;
                lastPiece.classList.add('last-move');
                
                // 添加一个小标记
                const marker = document.createElement('div');
                marker.classList.add('absolute', 'rounded-full', 'bg-highlight');
                marker.style.width = `${cellSize * 0.2}px`;
                marker.style.height = `${cellSize * 0.2}px`;
                marker.style.bottom = 0;
                marker.style.right = 0;
                lastPiece.appendChild(marker);
            }
            
            // 更新当前玩家指示器
            function updatePlayerIndicator() {
                if (currentPlayer === 1) {
                    currentPlayerIndicator.classList.remove('bg-white', 'border', 'border-gray-300');
                    currentPlayerIndicator.classList.add('bg-black');
                    currentPlayerText.textContent = '黑棋';
                } else {
                    currentPlayerIndicator.classList.remove('bg-black');
                    currentPlayerIndicator.classList.add('bg-white', 'border', 'border-gray-300');
                    currentPlayerText.textContent = '白棋';
                }
            }
            
            // 检查是否获胜
            let winPositions = []; // 存储获胜的五个棋子位置
            
            function checkWin(x, y, player) {
                const directions = [
                    [1, 0],   // 水平
                    [0, 1],   // 垂直
                    [1, 1],   // 对角线
                    [1, -1]   // 反对角线
                ];
                
                for (const [dx, dy] of directions) {
                    let count = 1; // 当前位置已经有一个棋子
                    winPositions = [{x, y}];
                    
                    // 正向检查
                    for (let i = 1; i < 5; i++) {
                        const newX = x + dx * i;
                        const newY = y + dy * i;
                        
                        if (
                            newX >= 0 && newX < BOARD_SIZE &&
                            newY >= 0 && newY < BOARD_SIZE &&
                            gameBoard[newY][newX] === player
                        ) {
                            count++;
                            winPositions.push({x: newX, y: newY});
                        } else {
                            break;
                        }
                    }
                    
                    // 反向检查
                    for (let i = 1; i < 5; i++) {
                        const newX = x - dx * i;
                        const newY = y - dy * i;
                        
                        if (
                            newX >= 0 && newX < BOARD_SIZE &&
                            newY >= 0 && newY < BOARD_SIZE &&
                            gameBoard[newY][newX] === player
                        ) {
                            count++;
                            winPositions.unshift({x: newX, y: newY});
                        } else {
                            break;
                        }
                    }
                    
                    // 如果连成五个，返回true
                    if (count >= 5) {
                        return true;
                    }
                    
                    // 重置当前方向的获胜位置
                    winPositions = [];
                }
                
                return false;
            }
            
            // 绘制胜利连线
            function drawWinLine() {
                if (winPositions.length < 5) return;
                
                // 获取第一个和最后一个点的坐标
                const start = winPositions[0];
                const end = winPositions[winPositions.length - 1];
                
                // 计算在棋盘上的实际位置
                const startX = start.x * cellSize + boardPadding;
                const startY = start.y * cellSize + boardPadding;
                const endX = end.x * cellSize + boardPadding;
                const endY = end.y * cellSize + boardPadding;
                
                // 计算线的长度和角度
                const length = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
                const angle = Math.atan2(endY - startY, endX - startX) * 180 / Math.PI;
                
                // 创建线元素
                const line = document.createElement('div');
                line.classList.add('absolute', 'bg-highlight');
                line.style.width = `${length}px`;
                line.style.height = `${cellSize * 0.1}px`;
                line.style.left = `${startX}px`;
                line.style.top = `${startY}px`;
                line.style.transformOrigin = '0 50%';
                line.style.transform = `translate(-50%, -50%) rotate(${angle}deg)`;
                line.style.zIndex = '10';
                line.style.borderRadius = '3px';
                
                // 添加到胜利线容器
                winLine.appendChild(line);
                
                // 高亮显示获胜的棋子
                highlightWinningPieces();
            }
            
            // 高亮显示获胜的棋子
            function highlightWinningPieces() {
                // 获取所有棋子
                const allPieces = pieces.querySelectorAll('div');
                
                // 遍历获胜位置并高亮对应的棋子
                winPositions.forEach(pos => {
                    // 计算棋子索引 (y * BOARD_SIZE + x)
                    const index = pos.y * BOARD_SIZE + pos.x;
                    
                    // 为获胜的棋子添加高亮效果
                    if (allPieces[index]) {
                        allPieces[index].classList.add('ring-4', 'ring-highlight');
                    }
                });
            }
            
            // 检查是否平局
            function checkDraw() {
                return movesCount === BOARD_SIZE * BOARD_SIZE;
            }
            
            // 显示获胜消息
            function showWinMessage(player) {
                gameResult.classList.remove('hidden');
                resultText.textContent = `${player === 1 ? '黑棋' : '白棋'}获胜！`;
                resultText.className = `font-medium text-center ${player === 1 ? 'text-black' : 'text-white bg-primary/80 px-2 py-1 rounded'}`;
                showNetworkMessage(`${player === 1 ? '黑棋' : '白棋'}获胜！`, player === playerId ? 'green' : 'red');
            }
            
            // 显示平局消息
            function showDrawMessage() {
                gameResult.classList.remove('hidden');
                resultText.textContent = '平局！';
                resultText.className = 'font-medium text-center text-accent';
                showNetworkMessage('平局！', 'blue');
            }
            
            // 重新开始游戏
            function restartGame() {
                if (!roomId) return;
                
                // 发送重新开始请求到服务器
                sendMessage({
                    type: 'restart_game'
                });
                
                // 显示加载动画
                loader.classList.remove('hidden');
            }
            
            // 悔棋
            function undoMove() {
                if (!roomId || moveHistory.length === 0 || !gameActive || currentPlayer !== playerId) {
                    return;
                }
                
                // 发送悔棋请求到服务器
                sendMessage({
                    type: 'undo_move'
                });
            }
            
            // 提示功能
            function showHint() {
                if (!gameActive || currentPlayer !== playerId) return;
                
                // 简单的提示算法：寻找当前玩家能形成四子的位置
                for (let y = 0; y < BOARD_SIZE; y++) {
                    for (let x = 0; x < BOARD_SIZE; x++) {
                        if (gameBoard[y][x] === 0) {
                            // 模拟落子
                            gameBoard[y][x] = currentPlayer;
                            
                            // 检查是否能形成四子
                            if (checkPotentialWin(x, y, currentPlayer, 4)) {
                                // 还原棋盘
                                gameBoard[y][x] = 0;
                                
                                // 显示提示标记
                                showHintMarker(x, y);
                                return;
                            }
                            
                            // 还原棋盘
                            gameBoard[y][x] = 0;
                        }
                    }
                }
                
                // 如果没有找到能形成四子的位置，寻找能阻止对手形成四子的位置
                const opponent = currentPlayer === 1 ? 2 : 1;
                for (let y = 0; y < BOARD_SIZE; y++) {
                    for (let x = 0; x < BOARD_SIZE; x++) {
                        if (gameBoard[y][x] === 0) {
                            // 模拟对手落子
                            gameBoard[y][x] = opponent;
                            
                            // 检查对手是否能形成四子
                            if (checkPotentialWin(x, y, opponent, 4)) {
                                // 还原棋盘
                                gameBoard[y][x] = 0;
                                
                                // 显示提示标记
                                showHintMarker(x, y);
                                return;
                            }
                            
                            // 还原棋盘
                            gameBoard[y][x] = 0;
                        }
                    }
                }
                
                // 如果没有找到上述位置，随机推荐一个位置
                const emptyPositions = [];
                for (let y = 0; y < BOARD_SIZE; y++) {
                    for (let x = 0; x < BOARD_SIZE; x++) {
                        if (gameBoard[y][x] === 0) {
                            emptyPositions.push({x, y});
                        }
                    }
                }
                
                if (emptyPositions.length > 0) {
                    const randomPos = emptyPositions[Math.floor(Math.random() * emptyPositions.length)];
                    showHintMarker(randomPos.x, randomPos.y);
                }
            }
            
            // 检查潜在的获胜机会
            function checkPotentialWin(x, y, player, requiredCount) {
                const directions = [
                    [1, 0],   // 水平
                    [0, 1],   // 垂直
                    [1, 1],   // 对角线
                    [1, -1]   // 反对角线
                ];
                
                for (const [dx, dy] of directions) {
                    let count = 1; // 当前位置已经有一个棋子
                    
                    // 正向检查
                    for (let i = 1; i < 5; i++) {
                        const newX = x + dx * i;
                        const newY = y + dy * i;
                        
                        if (
                            newX >= 0 && newX < BOARD_SIZE &&
                            newY >= 0 && newY < BOARD_SIZE &&
                            gameBoard[newY][newX] === player
                        ) {
                            count++;
                        } else {
                            break;
                        }
                    }
                    
                    // 反向检查
                    for (let i = 1; i < 5; i++) {
                        const newX = x - dx * i;
                        const newY = y - dy * i;
                        
                        if (
                            newX >= 0 && newX < BOARD_SIZE &&
                            newY >= 0 && newY < BOARD_SIZE &&
                            gameBoard[newY][newX] === player
                        ) {
                            count++;
                        } else {
                            break;
                        }
                    }
                    
                    // 如果达到要求的数量，返回true
                    if (count >= requiredCount) {
                        return true;
                    }
                }
                
                return false;
            }
            
            // 显示提示标记
            function showHintMarker(x, y) {
                // 先移除任何现有的提示
                document.querySelectorAll('.hint-marker').forEach(el => el.remove());
                
                // 创建提示标记
                const hint = document.createElement('div');
                hint.classList.add('hint-marker', 'absolute', 'rounded-full', 'bg-highlight/50', 'piece-transition');
                hint.style.width = `${cellSize * 0.6}px`;
                hint.style.height = `${cellSize * 0.6}px`;
                hint.style.left = `${x * cellSize + boardPadding}px`;
                hint.style.top = `${y * cellSize + boardPadding}px`;
                hint.style.transform = 'translate(-50%, -50%)';
                hint.style.zIndex = '5';
                
                // 添加到棋盘
                pieces.appendChild(hint);
                
                // 闪烁动画
                let opacity = 1;
                let decreasing = true;
                const blinkInterval = setInterval(() => {
                    if (decreasing) {
                        opacity -= 0.1;
                        if (opacity <= 0.5) decreasing = false;
                    } else {
                        opacity += 0.1;
                        if (opacity >= 1) decreasing = true;
                    }
                    hint.style.opacity = opacity;
                }, 200);
                
                // 5秒后自动移除提示
                setTimeout(() => {
                    clearInterval(blinkInterval);
                    hint.style.opacity = 0;
                    setTimeout(() => {
                        if (hint.parentNode) {
                            hint.parentNode.removeChild(hint);
                        }
                    }, 300);
                }, 5000);
            }
            
            // 网络相关函数
            function connectWebSocket() {
                // 使用公共测试WebSocket服务器
                // 注意：实际应用中应使用自己的WebSocket服务器
                socket = new WebSocket('wss://echo.websocket.events/');
                
                socket.onopen = () => {
                    console.log('WebSocket连接已打开');
                    isConnected = true;
                    updateConnectionStatus(true);
                    showNetworkMessage('已连接到服务器');
                };
                
                socket.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        handleServerMessage(data);
                    } catch (e) {
                        console.error('解析服务器消息失败:', e);
                        console.log('原始消息:', event.data);
                    }
                };
                
                socket.onclose = () => {
                    console.log('WebSocket连接已关闭');
                    isConnected = false;
                    updateConnectionStatus(false);
                    showNetworkMessage('与服务器的连接已关闭，正在尝试重连...', 'red');
                    
                    // 尝试重连
                    setTimeout(connectWebSocket, 5000);
                };
                
                socket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    showNetworkMessage('连接出现错误', 'red');
                };
            }
            
            function updateConnectionStatus(connected) {
                if (connected) {
                    connectionStatus.className = 'inline-block w-3 h-3 rounded-full bg-green-500 mr-2';
                    connectionText.textContent = '已连接';
                } else {
                    connectionStatus.className = 'inline-block w-3 h-3 rounded-full bg-red-500 mr-2';
                    connectionText.textContent = '未连接';
                }
            }
            
            function sendMessage(data) {
                if (!isConnected || !socket) {
                    showNetworkMessage('未连接到服务器，无法发送消息', 'red');
                    return false;
                }
                
                // 添加必要的元数据
                data.roomId = roomId;
                data.playerId = playerId;
                data.playerName = playerName;
                
                try {
                    socket.send(JSON.stringify(data));
                    return true;
                } catch (e) {
                    console.error('发送消息失败:', e);
                    showNetworkMessage('发送消息失败', 'red');
                    return false;
                }
            }
            
            function createRoom() {
                if (!isConnected) {
                    showNetworkMessage('请先连接到服务器', 'red');
                    return;
                }
                
                // 生成随机房间ID
                const newRoomId = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
                roomIdInput.value = newRoomId;
                
                // 发送创建房间请求
                sendMessage({
                    type: 'create_room',
                    roomId: newRoomId
                });
                
                showNetworkMessage(`正在创建房间 ${newRoomId}...`);
                loader.classList.remove('hidden');
            }
            
            function joinRoom() {
                if (!isConnected) {
                    showNetworkMessage('请先连接到服务器', 'red');
                    return;
                }
                
                const inputRoomId = roomIdInput.value.trim();
                if (!inputRoomId) {
                    showNetworkMessage('请输入房间ID', 'red');
                    return;
                }
                
                roomId = inputRoomId;
                
                // 发送加入房间请求
                sendMessage({
                    type: 'join_room',
                    roomId: roomId
                });
                
                showNetworkMessage(`正在加入房间 ${roomId}...`);
                loader.classList.remove('hidden');
            }
            
            function leaveRoom() {
                if (!roomId) return;
                
                // 发送离开房间请求
                sendMessage({
                    type: 'leave_room',
                    roomId: roomId
                });
                
                // 重置房间状态
                resetRoomState();
                showNetworkMessage('已离开房间');
            }
            
            function resetRoomState() {
                roomId = null;
                playerId = null;
                gameActive = false;
                
                // 更新UI
                player1NameEl.textContent = '等待中...';
                player2NameEl.textContent = '等待中...';
                yourRoleEl.textContent = '未分配';
                roomIdInput.value = '';
                
                // 重置游戏
                resetGameState();
            }
            
            function sendMove(x, y) {
                sendMessage({
                    type: 'make_move',
                    x: x,
                    y: y,
                    player: currentPlayer
                });
            }
            
            function showNetworkMessage(message, type = 'blue') {
                networkMessageEl.textContent = message;
                
                // 设置颜色
                networkMessageEl.className = 'text-sm';
                switch(type) {
                    case 'green':
                        networkMessageEl.classList.add('text-green-700', 'bg-green-50');
                        break;
                    case 'red':
                        networkMessageEl.classList.add('text-red-700', 'bg-red-50');
                        break;
                    case 'orange':
                        networkMessageEl.classList.add('text-orange-700', 'bg-orange-50');
                        break;
                    default:
                        networkMessageEl.classList.add('text-blue-700', 'bg-blue-50');
                }
            }
            
            function handleServerMessage(data) {
                console.log('收到服务器消息:', data);
                
                // 隐藏加载动画
                loader.classList.add('hidden');
                
                switch(data.type) {
                    case 'room_created':
                        roomId = data.roomId;
                        playerId = 1; // 创建者默认为黑棋
                        showNetworkMessage(`房间 ${roomId} 创建成功，等待其他玩家加入...`);
                        player1NameEl.textContent = playerName;
                        yourRoleEl.textContent = '黑棋 (玩家1)';
                        break;
                        
                    case 'room_joined':
                        playerId = data.playerId;
                        showNetworkMessage(`成功加入房间 ${roomId}`);
                        player1NameEl.textContent = data.players[1] || '等待中...';
                        player2NameEl.textContent = data.players[2] || '等待中...';
                        yourRoleEl.textContent = playerId === 1 ? '黑棋 (玩家1)' : '白棋 (玩家2)';
                        
                        // 如果房间已满，开始游戏
                        if (data.players[1] && data.players[2]) {
                            gameActive = true;
                            showNetworkMessage('房间已满，游戏开始！黑棋先行', 'green');
                        }
                        break;
                        
                    case 'player_joined':
                        showNetworkMessage(`玩家 ${data.playerName} 已加入房间`, 'green');
                        player1NameEl.textContent = data.players[1] || '等待中...';
                        player2NameEl.textContent = data.players[2] || '等待中...';
                        
                        // 如果房间已满，开始游戏
                        if (data.players[1] && data.players[2]) {
                            gameActive = true;
                            showNetworkMessage('房间已满，游戏开始！黑棋先行', 'green');
                        }
                        break;
                        
                    case 'player_left':
                        showNetworkMessage(`玩家 ${data.playerName} 已离开房间`, 'orange');
                        player1NameEl.textContent = data.players[1] || '等待中...';
                        player2NameEl.textContent = data.players[2] || '等待中...';
                        gameActive = false;
                        break;
                        
                    case 'move_made':
                        // 放置棋子
                        placePiece(data.x, data.y, data.player);
                        
                        // 记录历史
                        moveHistory.push({x: data.x, y: data.y, player: data.player});
                        
                        // 更新落子数
                        movesCount++;
                        movesCountEl.textContent = movesCount;
                        
                        // 检查是否获胜
                        if (checkWin(data.x, data.y, data.player)) {
                            gameActive = false;
                            showWinMessage(data.player);
                            drawWinLine();
                            return;
                        }
                        
                        // 检查是否平局
                        if (checkDraw()) {
                            gameActive = false;
                            showDrawMessage();
                            return;
                        }
                        
                        // 切换玩家
                        currentPlayer = currentPlayer === 1 ? 2 : 1;
                        updatePlayerIndicator();
                        
                        // 显示消息
                        if (currentPlayer === playerId) {
                            showNetworkMessage('轮到你落子了', 'green');
                        } else {
                            showNetworkMessage('等待对方落子...', 'blue');
                        }
                        break;
                        
                    case 'game_restarted':
                        resetGameState();
                        showNetworkMessage('游戏已重新开始，黑棋先行', 'green');
                        break;
                        
                    case 'move_undone':
                        // 移除最后一个棋子
                        if (pieces.lastChild) {
                            pieces.removeChild(pieces.lastChild);
                        }
                        
                        // 更新历史记录
                        if (moveHistory.length > 0) {
                            moveHistory.pop();
                        }
                        
                        // 更新游戏板
                        if (data.lastMove) {
                            gameBoard[data.lastMove.y][data.lastMove.x] = 0;
                        }
                        
                        // 更新落子数
                        movesCount--;
                        movesCountEl.textContent = movesCount;
                        
                        // 切换回上一个玩家
                        currentPlayer = data.currentPlayer;
                        updatePlayerIndicator();
                        
                        showNetworkMessage('已悔棋', 'blue');
                        break;
                        
                    case 'error':
                        showNetworkMessage(`错误: ${data.message}`, 'red');
                        break;
                        
                    default:
                        console.log('未知消息类型:', data.type);
                }
            }
            
            // 事件监听器
            restartBtn.addEventListener('click', restartGame);
            undoBtn.addEventListener('click', undoMove);
            hintBtn.addEventListener('click', showHint);
            leaveRoomBtn.addEventListener('click', leaveRoom);
            mobileRestartBtn.addEventListener('click', restartGame);
            mobileUndoBtn.addEventListener('click', undoMove);
            mobileHintBtn.addEventListener('click', showHint);
            createRoomBtn.addEventListener('click', createRoom);
            joinRoomBtn.addEventListener('click', joinRoom);
            
            // 窗口大小变化时重新调整棋盘
            window.addEventListener('resize', () => {
                const wasActive = gameActive;
                gameActive = false; // 防止调整大小时触发点击事件
                
                setTimeout(() => {
                    initializeBoard();
                    // 恢复游戏状态（除了棋盘大小）
                    gameActive = wasActive;
                }, 300);
            });
            
            // 初始化
            initializeBoard();
            connectWebSocket();
        });
    </script>
</body>
</html>
